﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using EPiBoost.Core.Model;
using EPiServer.Core;

namespace EPiBoost.Core.Helpers
{
	public static class PaginationHelper
	{
		public static Pagination GetPaginationLinks(PageDataCollection allPages, int defaultPageSize = 10, string pageIndexQueryStringKey = "pg", string pageSizeQueryStringKey = "ps")
		{
			var result = new Pagination(pageIndexQueryStringKey);

			if (allPages != null)
			{
				int pageIndex;
				int pageSize;

				TryGetValuesFromContext(pageIndexQueryStringKey, pageSizeQueryStringKey, defaultPageSize, out pageIndex, out pageSize);

				result.CurrentPageIndex = pageIndex;
				result.TotalPages = (int) Math.Ceiling(((decimal)allPages.Count/pageSize));
			}

			return result;
		}

		public static bool TryGetValuesFromContext(string pageIndexQueryStringKey, string pageSizeQueryStringKey, int defaultPageSize, out int pageIndex, out int pageSize)
		{
			pageIndex = 0;
			pageSize = defaultPageSize;
			if(HttpContext.Current!=null)
			{
				var indexString = HttpContext.Current.Request.QueryString[pageIndexQueryStringKey];
				if(!string.IsNullOrEmpty(indexString))
				{
					int.TryParse(indexString, out pageIndex);
				}

				var indexSize = HttpContext.Current.Request.QueryString[pageSizeQueryStringKey];
				if (!string.IsNullOrEmpty(indexSize))
				{
					int.TryParse(indexSize, out pageSize);
				}

				return true;
			}
			return false;
		}
	}
}
